package com.ruiysoft.security.service;

import com.alibaba.fastjson.JSON;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruiysoft.constant.IdentityConst;
import com.ruiysoft.entity.sys.*;
import com.ruiysoft.security.entity.IUserDetails;
import com.ruiysoft.service.sys.ISysMicroShopService;
import com.ruiysoft.service.sys.ISysShopPersonnelRelationService;
import com.ruiysoft.service.sys.ISysShopPersonnelService;
import com.ruiysoft.service.sys.redis.IRedisSysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;

/**
 * Created by 化增光 on 2018/10/28.
 */
@Service
public class RedisUserDetailsService implements UserDetailsService {

    private static Logger logger = LoggerFactory.getLogger(RedisUserDetailsService.class);

    @Resource
    IRedisSysUserService iRedisSysUserService;

    @Resource
    ISysShopPersonnelService iSysShopPersonnelService;

    @Resource
    ISysShopPersonnelRelationService iSysShopPersonnelRelationService;

    @Resource
    ISysMicroShopService iSysMicroShopService;

//    @Resource
//    ISysUserService iSysUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = iRedisSysUserService.selectSysUserByUserName(username);
        if (null == sysUser){
            throw new UsernameNotFoundException("未找到此用户");
        }
        if (!sysUser.getEnabled()){
            throw new UsernameNotFoundException("用户被禁用");
        }
        int loginType = 0;
        return new IUserDetails(sysUser.getUserName(), sysUser.getPassword(), sysUser.getId(),sysUser.getPersonnelId(), Arrays.asList(new SimpleGrantedAuthority(IdentityConst.SHOPKEEPER.toString())), sysUser.getEnabled(),loginType);
    }

//    public SysShopPersonnel loadShopPersonnelByOpenId(Long shopId, String openid) {
//        return iSysShopPersonnelService.selectOne(new EntityWrapper<SysShopPersonnel>().eq("shop_id",shopId).eq("openid",openid));
//    }

//    public void setCurrentLoginShop(String openid, Long shopId) {
//        iRedisSysUserService.setCurrentLoginShop(openid,shopId);
//    }

    public SysUser insertSysShopPersonnel(int loginType, Long shopId, Long sharingPersonnelId, String appId, String openid) {
        logger.debug("int loginType {}, Long shopId {}, Long sharingPersonnelId {}, String appId {}, String openid {}", loginType, shopId, sharingPersonnelId, appId, openid);
        SysUser user = null;
        SysShopPersonnel sysShopPersonnel = iRedisSysUserService.selectSysShopPersonnelByAppIdAndOpenId(appId,openid);
        if(logger.isDebugEnabled()){
            logger.debug("selectSysShopPersonnelByAppIdAndOpenId:{}", JSON.toJSONString(sysShopPersonnel));
        }
        if (null == sysShopPersonnel){
            sysShopPersonnel = this.insertPersonnel(appId,openid);
            if(logger.isDebugEnabled()){
                logger.debug("insertPersonnel:{}", JSON.toJSONString(sysShopPersonnel));
            }
        }else{
            user = selectSysUserByPersonnelId(sysShopPersonnel.getId());
            if(logger.isDebugEnabled()){
                logger.debug("user(selectSysUserByPersonnelId):{}", JSON.toJSONString(user));
            }
        }
        if (null == user){
            user = new SysUser();
            user.setPersonnelId(sysShopPersonnel.getId());
            user.setUserName("a:"+sysShopPersonnel.getAppId()+",o:"+sysShopPersonnel.getOpenid());
            user.setRealName(sysShopPersonnel.getNickname());
            user.setCreateTime(sysShopPersonnel.getCreateTime());
            //user.setPassword(sysShopPersonnel.getOpenid());
        }
        if (null != shopId){
            SysShopPersonnelRelation relation = selectShopPersonnelRelation(shopId,sysShopPersonnel.getId());
            if (null == relation){
                relation = new SysShopPersonnelRelation();
                relation.setPersonnelId(sysShopPersonnel.getId());
                relation.setShopId(shopId);
                // 指定分销关系我的下家
                relation.setParentId(sharingPersonnelId);

                iSysShopPersonnelRelationService.save(relation);
            }
            setCurrentLoginShop(loginType,user.getId(),sysShopPersonnel.getId(),shopId);
        }
        return user;
    }

//    private SysShopPersonnel updatePersonnel(SysShopPersonnel sysShopPersonnel, String nickname, String headImgUrl) {
//        sysShopPersonnel.setNickname(nickname);
//        sysShopPersonnel.setHeadImgUrl(headImgUrl);
//        System.out.println("进入 updatePersonnel"+ JSON.toJSONString(sysShopPersonnel));
//        iSysShopPersonnelService.updateById(sysShopPersonnel);
//        return sysShopPersonnel;
//    }

    // 新建用户
    private SysShopPersonnel insertPersonnel(String appId, String openid) {
        SysShopPersonnel sysShopPersonnel = new SysShopPersonnel()
                .setAppId(appId)
                .setOpenid(openid)
                .setCreateTime(new Date())
                .setUpdateTime(new Date())
                .setDeleteFlag(false)
                .setVersion(0);
        iSysShopPersonnelService.save(sysShopPersonnel);
        return sysShopPersonnel;
    }

    public void setCurrentLoginShop(int loginType, Long userId, Long personnelId, Long shopId) {
        iRedisSysUserService.setCurrentLoginShop(loginType,userId,personnelId,shopId);
    }

    public SysMicroShop selectSysMicroShopById(Long shopId) {
        return iSysMicroShopService.getById(shopId);
    }

    public SysShopPersonnelRelation selectShopPersonnelRelation(Long shopId, Long personnelId) {
        return iSysShopPersonnelRelationService.getOne(new QueryWrapper<SysShopPersonnelRelation>().eq("shop_id",shopId).eq("personnel_id",personnelId));
    }

    public SysUser selectSysUserByPersonnelId(Long personnelId) {
        return iRedisSysUserService.selectSysUserByPersonnelId(personnelId);
    }
}
